<template>
  <div class="about">
    <header>
      <i class="iconfont icon-fanhui" @click="$router.back()"></i>
      <input
        type="text"
        placeholder="请输入搜索内容"
        @blur="searchBtn"
        v-model="search"
        v-focus
      />
      <span></span>
    </header>
    <history v-if="list.length==0" @check="check"></history>
    <ul>
      <li v-for="(item, index) in list" :key="index">
        <img
          src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg4.bitautoimg.com%2Fautoalbum%2Ffiles%2F20180224%2F486%2F20180224172638263878461_5860927_16.jpg&refer=http%3A%2F%2Fimg4.bitautoimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1644713518&t=b19a5009d856f88bba0b8eae6526157f"
          alt=""
        />
        <section>
          <p>{{ item.goods_name }}</p>
          <span style="color: red">￥9.99</span>
        </section>
      </li>
    </ul>
  </div>
</template>

<script>
// @ is an alias to /src
// import axios from "axios";
import { reactive, toRefs,getCurrentInstance } from "vue";
import History from '../components/history.vue';
import { useStore } from 'vuex';
export default {
  name: "Home",
  components: {History},
  directives:{
    focus:{
      mounted(el) { // 自定义指令的生命周期，（也叫钩子函数）
        el.focus();
      },
    }
  },
  setup(props) {
    const { proxy } = getCurrentInstance();
    const store = useStore();
    const data = reactive({
      list: [],
      search: "", // 用户输入的值
    });

    const searchBtn = () => {
      // 搜索的函数
      proxy.$axios.get(`https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch?query=${data.search}`).then((res) => {
        if (data.search){ // 为空不让添加历史记录
            store.commit('addHistory',data.search);
        }
        data.list = res.data.message || [];
      });
    };
    const check = (val) => { // 历史记录的点击事件
      data.search = val;
      searchBtn();
    }
    return {
      ...toRefs(data),
      searchBtn,
      check
    };
  },
};
</script>
<style lang="scss" scoped>
.about {
  height: 100%;
  background: #e9e9e9;
}
header {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgb(255, 157, 0);
  span,
  i {
    width: 60px;
    text-align: center;
  }
  input {
    border: none;
    flex: 1;
    height: 40px;
    padding: 0 10px;
    background: #e9e9e9;
    border-radius: 20px;
    outline: none;
  }
}
ul {
  height: calc(100% - 50px);
  overflow: auto;
  li {
    display: flex;
    padding: 10px;
    background: #fff;
    margin-top: 10px;
    img {
      width: 90px;
      border-radius: 5px;
      margin-right: 10px;
    }
    section {
      flex: 1;
      p {
        width: 100%;
        font-size: 13px;
      }
    }
  }
}
</style>
